package main

import (
	"fmt"
	"os"
	"sanguo/cluster"
	"sanguo/node/common/db"
	"sanguo/node/node_dir"
	"sanguo/node/node_dir/server"
	"strconv"
	"strings"

	"github.com/go-ini/ini"
	"github.com/sniperHW/kendynet"
	"github.com/sniperHW/kendynet/golog"
)

func main() {

	if len(os.Args) < 2 {
		fmt.Printf("usage ./node_dir config\n")
		return
	}

	outLogger := golog.NewOutputLogger("log", "node_dir", 1024*1024*50)
	kendynet.InitLogger(outLogger, "node_dir")
	cluster.InitLogger(outLogger, "node_dir")
	node_dir.InitLogger(outLogger, "node_dir")

	cfg, err := ini.LooseLoad(os.Args[1])
	if err != nil {
		node_dir.Errorf("load %s failed:%s\n", os.Args[1], err.Error())
		return
	}

	secCommon := cfg.Section("Common")
	if nil == secCommon {
		node_dir.Errorf("missing sec[Common]\n")
		return
	}

	sec := cfg.Section(os.Args[2])
	if nil == sec {
		node_dir.Errorf("missing sec[%s]\n", os.Args[2])
		return
	}

	redisAddr := secCommon.Key("redisAddr").Value()
	centerAddr := secCommon.Key("centerAddr").Value()
	clusterAddr := sec.Key("clusterAddr").Value()
	externalAddr := sec.Key("externalAddr").Value()

	t := strings.Split(clusterAddr, ":")
	ip := t[0]
	fmt.Println(clusterAddr)
	port, _ := strconv.Atoi(t[1])

	filePath := sec.Key("filePath").Value()

	node_dir.Infoln(filePath)

	db.RedisInit(strings.Split(redisAddr, ","))

	//加载配置文件
	server.JsonParse(filePath)

	err = cluster.Start(strings.Split(centerAddr, ","), cluster.MakeService("dir", ip, int32(port)), true)

	if nil != err {
		node_dir.Errorf("node_dir start failed:%s\n", err.Error())
		return
	}

	err = node_dir.Start(externalAddr)

	if nil != err {
		node_dir.Errorf("server start failed:%s\n", err.Error())
	} else {
		node_dir.Infof("server start on %s\n", externalAddr)
		sigStop := make(chan bool)
		_, _ = <-sigStop
	}
}
